//
//  SEGPayManager.m
//  Commom
//
//  Created by 梁学彰 on 2020/4/8.
//

#import "SEGPayManager.h"

#import "UMSPPPayUnifyPayPlugin.h"

#import "UPAPayPlugin.h"

#import "CommonViewsHeader.h"
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

#if __has_include(<Commom/SEGBussinessConstHeader.h>)
#import <Commom/SEGBussinessConstHeader.h>
#else
#import "SEGBussinessConstHeader.h"
#endif

#import "SEGPlatformHeader.h"
#import "CommomHeader.h"
#import <SEGMediatorHeader.h>
#import <AlipaySDK/AlipaySDK.h>
#import <ICBCPaySDK.h>
#import "SEGThirdConfigManager.h"

//支付渠道
NSString * const kPayChannelWXORI          = @"WXORI";//微信原生支付
NSString * const kPayChannelUMSPAY_QMF     = @"UMSPAY_QMF";//银联聚合支付
NSString * const kPayChannelICBCPAY_APP    = @"ICBCPAY_APP";//工行支付
NSString * const kPayChannelBOHAI          = @"BOHAI";//渤海云账号(不走统一支付平台，仅作为前端支付渠道标识)

//支付方式
NSString * const kPayCodeALIPAY      = @"ALIPAY";//支付宝支付
NSString * const kPayCodeWEIXIN      = @"WEIXIN";//微信支付
NSString * const kPayCodeUAC         = @"UAC";//聚合支付
NSString * const kPayCodeICBCEPAY    = @"ICBCEPAY";//工行e支付

@interface SEGPayManager ()<ICBCPaySDKDelegate>

@end

@implementation SEGPayManager

+ (void)payWithParams:(NSDictionary*)dic payCode:(NSString*)payCode payChannel:(NSString *)payChannel {
    //没有包含paychannel的参数就走以前的微信支付
    if ((!payChannel||payChannel.length == 0)&&[payCode isEqualToString:kPayCodeWEIXIN]) {
        [self weixinPayWithParams:dic];
        return;
    }
    if ([payChannel containsString:kPayChannelUMSPAY_QMF]) {
        [self payWithUMSPAY_QMFParams:dic payCode:payCode];
        return;
    }else if ([payChannel containsString:kPayChannelWXORI]) {
        [self weixinPayWithParams:dic];
        return;
    }else if ([payChannel containsString:kPayChannelICBCPAY_APP]) {
        [self payWithICBCPAYParams:dic payCode:payCode];
        return;
    }else if ([payChannel containsString:kPayChannelBOHAI]) {
        
        NSMutableDictionary *payInfo = [NSMutableDictionary dictionary];
        [payInfo setValue:[ dic valueForKey:@"payType"] forKey:@"payType"];
        [payInfo setValue:[ dic valueForKey:@"transAmount"] forKey:@"transAmount"];
        [payInfo setValue:[ dic valueForKey:@"remark"] forKey:@"remark"];
        [payInfo setValue:[ dic valueForKey:@"orderNumber"] forKey:@"orderNumber"];
        [payInfo setValue:[ dic valueForKey:@"requestTime"] forKey:@"requestTime"];
        [payInfo setValue:kAccountUserID forKey:@"mUserId"];
        
        NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
        [dicM setValue:[[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil] forKey:@"vc"];
        [dicM setValue:payInfo forKey:@"payInfo"];
        
        [[SEGUhomeMediator sharedInstance] seg_BoHaiPayWithParams:dicM callBack:^(NSDictionary *responseData) {
            if (responseData && [responseData isKindOfClass:[NSDictionary class]]) {
                [[NSNotificationCenter defaultCenter]
                 postNotificationName: @"NSNotificationCenterName_BOHAI"
                 object:nil
                 userInfo:responseData];
            }
        }];
        
        return;
    }
        
    [SEGAlertView showTmepMessageWithMessage:@"暂时不支持此支付方式"];
    
}

+ (void)payWithUMSPAY_QMFParams:(NSDictionary*)dic payCode:(NSString *)payCode {
    if ([payCode isEqualToString:kPayCodeALIPAY]) {
        NSString *payDataJsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
        [UMSPPPayUnifyPayPlugin payWithPayChannel:CHANNEL_ALIPAY payData:payDataJsonStr callbackBlock:^(NSString *resultCode, NSString *resultInfo) {
            [self payUMSPAYResultWithResultCode:resultCode resultInfo:resultInfo];
        }];
    }else if ([payCode isEqualToString:kPayCodeWEIXIN]) {
        // 判断是否安装微信
        if (![WXApi isWXAppInstalled]) {
            UIAlertView* alertview = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"请先安装微信！"
                                                               delegate:nil
                                                      cancelButtonTitle:@"确认"
                                                      otherButtonTitles:nil];
            [alertview show];
            return;
        }
        NSString *payDataJsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
            [UMSPPPayUnifyPayPlugin payWithPayChannel:CHANNEL_WEIXIN
                                              payData:payDataJsonStr
                                        callbackBlock:^(NSString *resultCode, NSString *resultInfo) {
                [self payUMSPAYResultWithResultCode:resultCode resultInfo:resultInfo];
                                        }];

    }else if ([payCode isEqualToString:kPayCodeUAC]) {
        
        NSString *payDataJsonStr = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
        UIViewController *vc =  [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
        [UMSPPPayUnifyPayPlugin cloudPayWithURLSchemes:kOpenAppScheme
               payData:payDataJsonStr
        viewController:vc
         callbackBlock:^(NSString *resultCode, NSString *resultInfo) {
            [self payUMSPAYResultWithResultCode:resultCode resultInfo:resultInfo];
         }];
    }else {
        [SEGAlertView showTmepMessageWithMessage:@"暂时不支持此支付方式"];
    }
}

+ (void)payWithICBCPAYParams:(NSDictionary*)dic payCode:(NSString *)payCode {
    if ([payCode isEqualToString:kPayCodeALIPAY]) {
        if ([dic.allKeys containsObject:@"busistr"]) {
            NSString *orderString = [self base64DecodedString:ValueToString(dic[@"busistr"])].stringByURLDecode;
            NSString *msg_id = ValueToString(dic[@"msg_id"]);
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            for (NSString *object in [orderString componentsSeparatedByString:@"&"]) {
                NSString *key = [[object componentsSeparatedByString:@"="] firstObject];
                NSString *value = [[object componentsSeparatedByString:@"="] lastObject];
                if ([object componentsSeparatedByString:@"="].count != 2) {
                    NSMutableString *allString = [object mutableCopy];
                    [allString deleteCharactersInRange:NSMakeRange(0, key.length + 1)];
                    value = [allString copy];
                }
                [data setValue:value forKey:key];
            }
            [data setValue:msg_id forKey:@"msg_id"];
            [data setValue:kOpenAppScheme forKey:@"urlSchemes"];
            if ([data.allKeys containsObject:@"timestamp"]) {
                NSMutableString *timestamp = [data[@"timestamp"] mutableCopy];
                timestamp = [[timestamp stringByReplacingOccurrencesOfString:@"+" withString:@" "] mutableCopy];
                [data setValue:timestamp forKey:@"timestamp"];
            }
            NSLog(@"%@",data);
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
            if ([dic.allKeys containsObject:@"urlListenMain"]) {
                if (dic[@"urlListenMain"]) {
                    NSString *urlListenMain = dic[@"urlListenMain"];
                    [ICBCPaySDK sharedSdk].urlListMain = urlListenMain;
                }
            }
            [[ICBCPaySDK sharedSdk] presentAlipaySDKViewController:vc andTraderInfo:data];
        }
    }else if ([payCode isEqualToString:kPayCodeICBCEPAY]) {
        if ([dic.allKeys containsObject:@"iosstr"]) {
            NSString *orderString = [self base64DecodedString:ValueToString(dic[@"iosstr"])].stringByURLDecode;
            NSString *msg_id = ValueToString(dic[@"msg_id"]);
            NSMutableDictionary *data = [NSMutableDictionary dictionary];
            for (NSString *object in [orderString componentsSeparatedByString:@"&"]) {
                NSString *key = [[object componentsSeparatedByString:@"="] firstObject];
                NSString *value = [[object componentsSeparatedByString:@"="] lastObject];
                if ([object componentsSeparatedByString:@"="].count != 2) {
                    NSMutableString *allString = [object mutableCopy];
                    [allString deleteCharactersInRange:NSMakeRange(0, key.length + 1)];
                    value = [allString copy];
                }
                [data setValue:value forKey:key];
            }
            [data setValue:msg_id forKey:@"msg_id"];
            [data setValue:kOpenAppScheme forKey:@"urlSchemes"];
            if ([data.allKeys containsObject:@"timestamp"]) {
                NSMutableString *timestamp = [data[@"timestamp"] mutableCopy];
                timestamp = [[timestamp stringByReplacingOccurrencesOfString:@"+" withString:@" "] mutableCopy];
                [data setValue:timestamp forKey:@"timestamp"];
            }
            NSLog(@"%@",data);
            UIViewController *vc = [[SEGUhomeMediator sharedInstance] seg_getCurrentController:nil];
            if ([dic.allKeys containsObject:@"urlListenMain"]) {
                if (dic[@"urlListenMain"]) {
                    NSString *urlListenMain = dic[@"urlListenMain"];
                    [ICBCPaySDK sharedSdk].urlListMain = urlListenMain;
                }
            }
            [ICBCPaySDK sharedSdk].sdkDelegate = [SEGThirdConfigManager sharedInstance];
            [ICBCPaySDK sharedSdk].urlPortal= @"https://b2c.icbc.com.cn";
            [[ICBCPaySDK sharedSdk] presentICBCPaySDKInViewController:vc andTraderInfo:data];
        }
    }else {
        [SEGAlertView showTmepMessageWithMessage:@"暂时不支持此支付方式"];
    }
}


+ (void)weixinPayWithParams:(NSDictionary*)dic
{
    // 判断是否安装微信
    if (![WXApi isWXAppInstalled]) {
        UIAlertView* alertview = [[UIAlertView alloc] initWithTitle:@""
                                                            message:@"请先安装微信！"
                                                           delegate:nil
                                                  cancelButtonTitle:@"确认"
                                                  otherButtonTitles:nil];
        [alertview show];
        return;
    }
    PayReq* request = [[PayReq alloc] init];
    request.partnerId = [dic objectForKey:@"partnerid"];
    request.prepayId = [dic objectForKey:@"prepayid"];
    request.nonceStr = [dic objectForKey:@"noncestr"];
    request.timeStamp = (UInt32)[ValueToString([dic objectForKey:@"timestamp"]) intValue];;
    request.package = [dic objectForKey:@"package"];
    request.sign = [dic objectForKey:@"sign"];

    [WXApi sendReq:request completion:nil];
}

+ (void)payUMSPAYResultWithResultCode:(NSString *)resultCode resultInfo:(NSString *)resultInfo {
    if (resultCode.integerValue == 0) {
        NSNotification* notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"success"];
        [[NSNotificationCenter defaultCenter] postNotification:notification];
    }else {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            NSData *jsonData = [resultInfo dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            if(err) {
                NSLog(@"json解析失败：%@",err);
                [SEGAlertView showTmepMessageWithMessage:resultInfo withtime:2.0];
                return;
            }else {
                if ([[dic allKeys] containsObject:@"resultMsg"]&&[dic valueForKey:@"resultMsg"]&&[[dic valueForKey:@"resultMsg"] isKindOfClass:[NSString class]]) {
                    [SEGAlertView showTmepMessageWithMessage:[dic valueForKey:@"resultMsg"] withtime:2.0];
                }
            }
        });
    }
}

+ (NSString *)base64DecodedString:(NSString *)base64String {
  NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
  return [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
}




@end
